﻿using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Windows;
using System.Windows.Input;
using Microsoft.Phone.UserData;
using MobiSms.DataModel;
using MobiSms.Enums;
using MobiSms.Library;
using System;

namespace MobiSms.ViewModel
{
    public class RecentBirthdayViewModel : ViewModelBase
    {
        private Contacts contacts = new Contacts();

        public RecentBirthdayViewModel()
        {
            contacts.SearchCompleted -= contacts_SearchCompleted;
            contacts.SearchCompleted += contacts_SearchCompleted;

            if (!IsDesignMode)
            {
                contacts.SearchAsync("", FilterKind.None, null);
            }
        }

        private ObservableCollection<ContactInfo> _itemsOfContact = new ObservableCollection<ContactInfo>();
        public ObservableCollection<ContactInfo> ItemsOfContact
        {
            get { return _itemsOfContact; }
            set
            {
                _itemsOfContact = value;
                RaisePropertyChanged(() => ItemsOfContact);
            }
        }

        private void contacts_SearchCompleted(object sender, ContactsSearchEventArgs e)
        {
            IEnumerable<Contact> items = e.Results.Where(c => c.Birthdays != null && c.Birthdays.Count() > 0 && c.PhoneNumbers != null && c.PhoneNumbers.Count() > 0);
            foreach (Contact item in items)
            {
                DateTime original = item.Birthdays.FirstOrDefault();
                DateTime birthday = new DateTime(DateTime.Now.Year, original.Month, original.Day);
                if (birthday > DateTime.Today && birthday < DateTime.Today.AddDays(GlobalSettings.NotifyDays))
                {
                    ItemsOfContact.Add(new ContactInfo() { Birthday = birthday, Mobile = item.PhoneNumbers.FirstOrDefault().PhoneNumber, Name = item.DisplayName });
                }
            }
        }
    }
}
